package com.ruoyi.qywx.getway.api;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.constant.ErrorConstants;
import com.ruoyi.common.core.cache.Meta;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.qywx.getway.entity.QyExtContactRemark;
import com.ruoyi.qywx.getway.request.TxRequest;
import com.ruoyi.qywx.getway.request.TxResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @author : hcl
 * @Date : 2023/8/18 10:29
 * 标签api
 * 备注api
 */
@Slf4j
public class ContactTagApi {
    /**
     * 暂时预留，后期看是否需要：不清理分组下标签，直接删除分组
     */
    public static void deleteGroupTag(String wxId, Meta meta) {
        Map<String, List<String>> body = Collections.singletonMap("group_id", Collections.singletonList(wxId));
        delete(meta, JSONUtil.toJsonStr(body));
    }

    /**
     * 删除企业微信标签
     * https://qyapi.weixin.qq.com/cgi-bin/tag/delete?access_token=ACCESS_TOKEN&tagid=TAGID
     */
    public static void deleteTag(String wxId, Meta meta) {
        Map<String, List<String>> body = Collections.singletonMap("tag_id", Collections.singletonList(wxId));
        delete(meta, JSONUtil.toJsonStr(body));
    }

    private static void delete(Meta meta, String body) {
        if (meta == null) {
            throw new ServiceException(ErrorConstants.META_NOT_FOUND);
        }
        TxResponse post = TxRequest.getInstance(meta.getCorpid(), meta.getAppSecret())
                .post("/cgi-bin/externalcontact/del_corp_tag", body);
        if (!post.isSuccess()) {
            throw new ServiceException(post.getJson().toString());
        }
    }

    /**
     * https://developer.work.weixin.qq.com/document/path/92117#%E6%B7%BB%E5%8A%A0%E4%BC%81%E4%B8%9A%E5%AE%A2%E6%88%B7%E6%A0%87%E7%AD%BE
     *
     * @param name      标签名称
     * @param wxId      标签组id
     * @param groupName 新分组不存在wxid 使用分组名称
     * @return 分组id
     */
    public static JSONObject insertTag(Meta meta, String name, String wxId, String groupName) {
        if (meta == null) {
            throw new ServiceException(ErrorConstants.META_NOT_FOUND);
        }
        Map<String, Object> body = new HashMap<>();
        if (StrUtils.isNotEmpty(wxId)) {
            body.put("group_id", wxId);
        } else {
            body.put("group_name", groupName);
        }
        body.put("tag", Collections.singletonList(Collections.singletonMap("name", name)));
        TxResponse post = TxRequest.getInstance(meta.getCorpid(), meta.getAppSecret())
                .post("/cgi-bin/externalcontact/add_corp_tag", JSONUtil.toJsonStr(body));
        if (!post.isSuccess()) {
            throw new ServiceException(post.getJson().toString());
        }
        return post.getJson();
    }

    /**
     * https://developer.work.weixin.qq.com/document/path/92117#%E7%BC%96%E8%BE%91%E4%BC%81%E4%B8%9A%E5%AE%A2%E6%88%B7%E6%A0%87%E7%AD%BE
     *
     * @param wxId 标签id
     * @param name 标签名称
     */
    public static void updateTagOrGroupName(Meta meta, String wxId, String name) {
        if (meta == null) {
            throw new ServiceException(ErrorConstants.META_NOT_FOUND);
        }
        Map<String, String> body = new HashMap<>();
        body.put("id", wxId);
        body.put("name", name);
        TxResponse post = TxRequest.getInstance(meta.getCorpid(), meta.getAppSecret())
                .post("/cgi-bin/externalcontact/edit_corp_tag", JSONUtil.toJsonStr(body));
        if (!post.isSuccess()) {
            throw new ServiceException(post.getJson().toString());
        }
    }

    /**
     * 绑定或者移除标签
     * https://developer.work.weixin.qq.com/document/path/92697
     */
    public static boolean extUserMarkTags(String extUserId, String userId,
                                          List<String> bindTags, List<String> removeTags,
                                          Meta meta) {
        if (CollectionUtils.isAllEmpty(bindTags, removeTags)) {
            return true;
        }
        Map<String, Object> body = new HashMap<>();
        if (CollectionUtils.isNotEmpty(bindTags)) {
            body.put("add_tag", bindTags);
            log.info("bind tag: {}", CollectionUtils.join(bindTags, StrUtils.COMMA));
        }
        if (CollectionUtils.isNotEmpty(removeTags)) {
            body.put("remove_tag", removeTags);
            log.info("remove tag: {}", CollectionUtils.join(removeTags, StrUtils.COMMA));

        }
        if (CollectionUtils.isNotEmpty(body)) {
            body.put("userid", userId);
            body.put("external_userid", extUserId);
            TxResponse post = TxRequest.getInstance(meta.getCorpid(), meta.getAppSecret())
                    .post("/cgi-bin/externalcontact/mark_tag", JSONUtil.toJsonStr(body));
            if (post.isSuccess()) {
                return true;
            }
            log.error("绑定标签失败,员工：{},客户:{},错误信息:{}", userId, extUserId, post.getError());
        }
        return false;
    }

    /**
     * 修改备注信息
     * https://developer.work.weixin.qq.com/document/path/92694
     */
    public static boolean editExternalContactRemark(Meta meta, QyExtContactRemark remark) {
        TxResponse post = TxRequest.getInstance(meta.getCorpid(), meta.getAppSecret())
                .post("/cgi-bin/externalcontact/remark", JSONUtil.toJsonStr(remark));
        if (post.isSuccess()) {
            return true;
        }
        log.error("编辑备注失败,员工：{},客户:{},错误信息:{}", remark.getExternal_userid(),
                remark.getUserid(),
                post.getError());
        return false;
    }
}
